package com.yeyaomai.dksns.flowis.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisStatDetailDTO;
import com.yeyaomai.dksns.flowis.service.FlowisQueryService;
import com.yeyaomai.dksns.flowis.service.result.KeyWordGain;
import com.yeyaomai.dksns.flowis.util.CollectionNames;

/**
 * 原始数据处理类
 * 
 * @author xiaqin
 * @date 2012.05.23
 */
@Controller
public class BaseController {

	@Autowired
	FlowisQueryService flowisQueryService;

	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	@RequestMapping("/getData")
	public void getData(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String existip = request.getRemoteAddr();
		if(existip.equals("115.236.161.18"))
		{
			response.getWriter().print("0");
		}
		else{
		Date dates = new Date();
		String data = request.getParameter("data");
		JSONObject object = JSONObject.fromObject(data);
		String refer = object.getString("refer");
		String accessUrl = object.getString("path");
		FlowisStatDetailDTO flow = new FlowisStatDetailDTO();
		if(accessUrl.indexOf("web_id") != -1)
		{
			int startSite = accessUrl.lastIndexOf("web_id")+7;
			int endSite = accessUrl.indexOf("&");
			String web_Id ="";
			if(startSite < endSite)
			{
				 web_Id = accessUrl.substring(startSite, endSite);
			}
			else{
				 web_Id = accessUrl.substring(startSite, accessUrl.length());
			}
			
			flow.setWeb_Id(web_Id);
		}
		String domain ="";
		if (!refer.equals("")) {
			String[] data1 = refer.split("//");
			String[] data2 = data1[1].split("/");
			domain = data2[0];
		}
		flow.setDomain(domain);
		flow.setReferer(refer);
		// flow.setPageName(object.getString("page"));
		// flow.setCookieId(object.getString("cookieID"));
		flow.setAccess_url(accessUrl);
		flow.setOs(object.getString("os"));
		// flow.setStoptime(object.getString("stoptime"));
		flow.setBrowser(object.getString("browser"));
		flow.setPlatform(object.getString("platform"));
		flow.setLanguage(object.getString("lg"));
		flow.setScreen_resolution(object.getString("screenres"));
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		flow.setAccess_date(date.format(new Date()));
		String keyword = "";
		String engineName = "";
		Integer req_source = 0;
		if (!refer.equals("")) {
			String engine = KeyWordGain.getDomain(domain);
			  if (engine.equals("端口")) {
				engineName = engine;
				keyword = KeyWordGain.getKeyword(refer);
				req_source = CollectionNames.DIRECTTYPE;
			} else if (engine.equals("")) {
				req_source = CollectionNames.OUTTYPE;
			}
			  else {
				  engineName = engine;
				  keyword = KeyWordGain.getKeyword(refer);
				  req_source = CollectionNames.ENGIETYPE;
			}
		} else {
			req_source = CollectionNames.DIRECTTYPE;
		}
		// String plugins = object.getString("plugins");//暂时未用
		// String flash = object.getString("flash");
		String ip = getIpAddr(request);
		flow.setIp(ip);
		flow.setWebModule(this.getModule(accessUrl));
		flow.setEngineName(engineName);
		flow.setKeyword(keyword);
		flow.setReq_source(req_source);
		flow.setAccess_country(null);
		flow.setAccess_province(null);
		flow.setAccess_city(null);
		//getValueByIp(flow, ip);

		Cookie cookies[] = request.getCookies();
		Cookie c = null;
		Map<String, String> map = new HashMap<String, String>();
		if (null != cookies) {
			for (int i = 0; i < cookies.length; i++) {
				c = cookies[i];
				if (c.getName().equals("duankouId")
						|| c.getName().equals("visitCount")
						|| c.getName().equals("currentState")) {
					map.put(c.getName(), c.getValue());
				}

			}
		}

		boolean isfirst = true;
		int returncount = 1;
		flow.setVisitCount(1);
		flow.setReturnNumber(returncount);
		if (map.size() > 0) {
			String duankouId = map.get("duankouId");
			String visitNum = map.get("visitCount");
			String currentStateNum = map.get("currentState");
			if (duankouId != null) {
				c = new Cookie("duankouId", map.get("duankouId"));
				isfirst = false;
				String duankou[] = duankouId.split("\\.");
				long number = dates.getTime() - Long.valueOf(duankou[3]);
				flow.setCookieId(duankou[0]);
				flow.setVisitCount(Integer.valueOf(duankou[4]));
				flow.setDomainId(currentStateNum);
				// 当前时间距最后一次访问时间大于十二小时就把回头率在原有的基础上加一
				if (number >= 43200000) {
					returncount = Integer.valueOf(duankou[5]) + 1;
					c.setValue(duankou[0] + "." + duankou[1] + "." + duankou[3]
							+ "." + dates.getTime() + "." + duankou[4] + "."
							+ returncount);
					c.setMaxAge(31536000);
					response.addCookie(c);
					flow.setReturnNumber(returncount);
				}
				if (visitNum == null && currentStateNum == null) {
					int count = Integer.valueOf(duankou[4]) + 1;
					c.setValue(duankou[0] + "." + duankou[1] + "." + duankou[3]
							+ "." + dates.getTime() + "." + count + "."
							+ duankou[5]);

					Cookie visitCount = new Cookie("visitCount", "1");
					visitCount.setMaxAge(1800);// 1800
					String domainId = UUID.randomUUID().toString();
					Cookie currentState = new Cookie("currentState", domainId);
					c.setMaxAge(31536000);
					response.addCookie(c);
					response.addCookie(visitCount);
					response.addCookie(currentState);
					flow.setVisitCount(count);
				}
			}
		}

		if (isfirst) {
			String id = UUID.randomUUID().toString();
			// 分别为第一次访问时间,上次访问时间,最近一次访问时间,访问次数,回访次数
			Cookie cookie = new Cookie("duankouId", id + "." + dates.getTime()
					+ "." + dates.getTime() + "." + dates.getTime() + ".1.1");
			cookie.setMaxAge(31536000);
			Cookie visitCount = new Cookie("visitCount", "1");
			visitCount.setMaxAge(1800);// 1800
			String domainId = UUID.randomUUID().toString();
			Cookie currentState = new Cookie("currentState", domainId);
			flow.setVisitCount(1);
			flow.setCookieId(id);
			flow.setDomainId(domainId);
			response.addHeader("P3P", "CP=CAO PSA OUR");
			response.addCookie(cookie);
			response.addCookie(visitCount);
			response.addCookie(currentState);
		}
		response.getWriter().print("xuanlumeng");
		flowisQueryService.insert(flow);
		try {
			response.getWriter().print("1");
		} catch (Exception e) {
			try {
				response.getWriter().print("0");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		}
	}

	public static void getValueByIp(FlowisStatDetailDTO flow, String ip) {

		try {
			URL url = new URL("http://whois.pconline.com.cn/ipJson.jsp?ip="
					+ ip);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream(), "GBK"));
			String getvalue = reader.readLine();
			String json = getvalue.substring(34, getvalue.length() - 3);
			JSONObject object = JSONObject.fromObject(json);
			String addr = object.getString("addr");
			String pro = object.getString("pro");
			String city = object.getString("city");
			flow.setAccess_country("中国");
			flow.setInternet_provider("其它");
			if (pro.equals("")) {
				flow.setAccess_country(addr);
			} else {
				String addrs[] = addr.split(" ");
				if(addrs.length > 1)
				{
					flow.setInternet_provider(addrs[1]);
				}
			}
			flow.setAccess_province(pro);
			flow.setAccess_city(city);
			reader.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取客户端IP
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			logger.info("type:Proxy-Client-IP##########IP:"+ip);
		}
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			logger.info("type:WL-Proxy-Client-IP##########IP:"+ip);
		}
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
			logger.info("type:HTTP_CLIENT_IP##########IP:"+ip);
		}
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			logger.info("type:HTTP_X_FORWARDED_FOR##########IP:"+ip);
		}
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			logger.info("type:RemoteAddr##########IP:"+ip);
		}
		return ip;
	}

	private Integer getModule(String access_url)
	{
		Integer module = null;
		if(access_url.indexOf("dkads.duankou.com") != -1)
			module = 1;
		else if(access_url.indexOf("credit.duankou.com") != -1)
			module = 2;
		else if(access_url.indexOf("wiki.duankou.com") != -1)
			module = 3;
		else if(access_url.indexOf("interest.duankou.com") != -1)
			module = 4;
		else if(access_url.indexOf("group.duankou.com") != -1)
			module = 5;
		else if(access_url.indexOf("favorite") != -1)
			module = 6;
		else if(access_url.indexOf("netdisk.duankou.com") != -1)
			module = 7;
		else if(access_url.indexOf("album.duankou.com") != -1)
			module = 8;
		else if(access_url.indexOf("walbum.duankou.com") != -1)
			module = 9;
		else if(access_url.indexOf("video.duankou.com") != -1)
			module = 10;
		else if(access_url.indexOf("wvideo.duankou.com") == 0)
			module = 11;
		else if(access_url.indexOf("event.duankou.com") != -1)
			module = 12;
		else if(access_url.indexOf("gevent.duankou.com") != -1)
			module = 13;
		else if(access_url.indexOf("wevent.duankou.com") != -1)
			module = 14;
		else if(access_url.indexOf("webmain.duankou.com") != -1)
			module = 15;
		else if(access_url.indexOf("profile") != -1)
			module = 16;
		else if(access_url.indexOf("setting") != -1 )
			module = 17;
		else if(access_url.indexOf("user.duankou.com") != -1)
			module = 18;
		else if( access_url.indexOf("notice") != -1)
			module = 19;
		else if(access_url.indexOf("ask.duankou.com") != -1)
			module = 20;
		else if(access_url.indexOf("channel.duankou.com") != -1)
			module = 21;
		else if(access_url.indexOf("pay.duankou.com") != -1)
			module = 22;
		else if(access_url.indexOf("following") != -1 || access_url.indexOf("follower") != -1 || access_url.indexOf("friend") != -1)
			module = 23;
		else if(access_url.indexOf("msg") != -1)
			module = 24;
		else if(access_url.indexOf("blog.duankou.com") != -1)
			module = 25;
		else if(access_url.indexOf("leavemsg") != -1)
			module = 26;
		else if(access_url.indexOf("invite") != -1)
			module = 27;
		else if(access_url.indexOf("help") != -1)
			module = 28;
		else if(access_url.indexOf("search") != -1)
			module = 30;
		else if(access_url.indexOf("app.duankou.com") != -1)
			module = 31;
		else if(access_url.indexOf("api.duankou.com") != -1)
			module = 32;
		else if(access_url.indexOf("open.duankou.com") != -1)
			module = 33;
		else 
			module = 29;
		return module;
	}
	public static void main(String[] args) {
//		System.out.println(new BaseController().getModule("http://www.duankou.com/100297/index/profile"));
	}
}
